package com.edee.bigday.order.listener;

import com.edee.bigday.order.entity.OrderEntity;
import com.edee.bigday.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "order.release.order.queue")
@Service
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    /**
     * @param orderEntity
     * @param channel     由于消息队列开启了手动确认模式，所以，需要打开通道Channel
     * @param message
     * @throws IOException
     */
    //@RabbitListener(queues = "order.release.order.queue")
    @RabbitHandler
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        System.out.println("收到过期的订单信息，准备关闭订单：" + orderEntity.getOrderSn());
        try {
            orderService.closeOrder(orderEntity);
            //手动调用支付宝的统一收单交易关闭接口
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            //遇到任何异常，拒绝消息并重新入队：
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
